package net.seehope.foodie.code.authentication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import net.seehope.foodie.properties.ProjectConstant;

public class SmsCodeAuthenticationFilter extends
AbstractAuthenticationProcessingFilter {


public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "mobile";

private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
private boolean postOnly = true;

public SmsCodeAuthenticationFilter() {
super(new AntPathRequestMatcher(ProjectConstant.MOBILE_AUTHENTICATION_URL, "POST"));
}


public Authentication attemptAuthentication(HttpServletRequest request,
	HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
	throw new AuthenticationServiceException(
			"Authentication method not supported: " + request.getMethod());
}

String username = obtainUsername(request);


if (username == null) {
	username = "";
}

username = username.trim();

SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(username);

// Allow subclasses to set the "details" property
setDetails(request, authRequest);

return this.getAuthenticationManager().authenticate(authRequest);
}


@Nullable
protected String obtainPassword(HttpServletRequest request) {
return null;
}


@Nullable
protected String obtainUsername(HttpServletRequest request) {
return request.getParameter(usernameParameter);
}


protected void setDetails(HttpServletRequest request,
		SmsCodeAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}


public void setUsernameParameter(String usernameParameter) {
Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
this.usernameParameter = usernameParameter;
}


public void setPasswordParameter(String passwordParameter) {

}

public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}

public final String getUsernameParameter() {
return usernameParameter;
}

public final String getPasswordParameter() {
return null;
}
}

